﻿/*
*	Author(作者)：gzj
*	Description(描述)：
*	Version(版本):
*	LogicFlow(逻辑流程):
*	TODO:
*/
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using System.IO;
using System.Text;

public class NamespaceEx : EditorWindow
{

    [MenuItem("Tools/命名空间/修改脚本命名空间")]
    public static void Init()
    {
        NamespaceEx window = (NamespaceEx)EditorWindow.GetWindow(typeof(NamespaceEx));
        window.Show();
    }

    string dirPath;
    string filePath;
    string nameSpaceStr;
    bool isModifyDir = true;

    private void OnGUI()
    {
        isModifyDir = EditorGUILayout.Toggle("修改文件夹或单个文件：", isModifyDir);

        if (isModifyDir)
            dirPath = EditorGUILayout.TextField("需修改的文件夹[绝对路径]:", dirPath);
        else
            filePath = EditorGUILayout.TextField("需要修改的文件文件[绝对路径]:", filePath);

        nameSpaceStr = EditorGUILayout.TextField("命名空间字符串:", nameSpaceStr);

        if (GUILayout.Button("修改命名空间[限制：只能给没有命名空间的脚本添加命名空间]"))
        {
            if (isModifyDir)
                ModifyDir();
            else
                ModifyFile(filePath);
        }
    }

    void ModifyDir()
    {
        if (string.IsNullOrEmpty(dirPath))
        {
            Debug.LogError("dirPath can no null");
            return;
        }

        string dir = Path.GetDirectoryName(dirPath);
        if (!Directory.Exists(dir))
        {
            Debug.LogError($"dirPath  no exist,{dirPath}");
            return;
        }
        if (string.IsNullOrEmpty(nameSpaceStr))
        {
            Debug.LogError("nameSpaceStr can no null");
            return;
        }

        string[] files = Directory.GetFiles(dirPath, "*", SearchOption.AllDirectories);
        foreach (var item in files)
        {
            if (item.EndsWith(".cs"))
            {
                ModifyFile(item);
            }
        }

        Debug.Log($"文件夹:{dirPath} 命名空间修改成功");
    }

    void ModifyFile(string filePath)
    {
        if (string.IsNullOrEmpty(filePath))
        {
            Debug.LogError("filePath can no null");
            return;
        }

        if (!File.Exists(filePath))
        {
            Debug.LogError($"filePath can no exist,{filePath}");
            return;
        }
        if (string.IsNullOrEmpty(nameSpaceStr))
        {
            Debug.LogError("nameSpaceStr can no null");
            return;
        }
        if (!filePath.EndsWith(".cs"))
        {
            return;
        }

        StringBuilder sb = new StringBuilder();
        sb.AppendLine($"namespace {nameSpaceStr}");
        sb.AppendLine("{");

        string content = File.ReadAllText(filePath);

        sb.Append(content);

        sb.AppendLine("}");

        File.WriteAllText(filePath, sb.ToString());
        AssetDatabase.Refresh();

        Debug.Log($"文件:{filePath} 的命名空间修改成功");
    }
}
